﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Runtime.Serialization;

namespace OpenQuarters.WebQuarters.Utils
{
    /// <summary>
    /// Defines a generic dictionary that does not throw exceptions if an index does not exist
    /// </summary>
    /// <typeparam name="T1"></typeparam>
    /// <typeparam name="T2"></typeparam>
    [Serializable]
    public class FriendlyDictionary<T1, T2> : Dictionary<T1, T2>
    {
        public delegate T2 GetNewObjectHandler(T1 key);

        public event GetNewObjectHandler OnGetNewObject;

        private T2 GetNewObject(T1 key)
        {
            if (OnGetNewObject != null)
            {
                return OnGetNewObject.Invoke(key);
            }
            return GeneralUtils.GetNewObject<T2>();
        }

        public new T2 this[T1 key]
        {
            get
            {
                if (!this.ContainsKey(key))
                {
                    this.Add(key, GetNewObject(key));
                }
                return base[key];
            }
            set
            {
                if (!this.ContainsKey(key))
                {
                    this.Add(key, GetNewObject(key));
                }
                base[key] = value;
            }
        }

        public FriendlyDictionary()
            : base()
        {
        }

        public FriendlyDictionary(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}
